#include<iostream>
#include<vector>
#include<algorithm>

using namespace std;
struct Node{
	int addr,data;
	Node(int addr,int data):addr(addr),data(data){}
};
vector<Node> N;

int addr[100005],Data[100005],Next[100005]={-2};
int main(){

	freopen("input.txt","r",stdin);
	int addr_1;
	int n,k;
	cin>>addr_1>>n>>k;
	for(int i=0;i<n;i++){
		int temp;
		cin>>temp;
		cin>>Data[temp];//data
		cin>>Next[temp];// next
	}
	Node N1=Node(addr_1,Data[addr_1]);
	N.push_back(N1);int sum=0;
	int addr_c=Next[addr_1];
	while(addr_c!=-1){
		N1.addr=addr_c;
		N1.data=Data[addr_c];
		addr_c=Next[addr_c];
		sum++;
		N.push_back(N1);
	}
	for(int i=0;i+k<=sum+1;i=i+k){
		reverse(N.begin()+i,N.begin()+k+i);
	}
	int flag=0;
	for(auto i :N){
		if(flag==0){
			flag=1;
		}else{
			printf("%05d\n",i.addr);
		}
		printf("%05d %d ",i.addr,i.data);
	}
	cout<<-1<<endl;
	return 0;
}